package com.distribution.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.distribution.common.core.domain.entity.SysUser;
import com.distribution.system.domain.SysNotice;
import com.distribution.system.domain.entity.NoticeUserManage;
import com.distribution.system.mapper.NoticeUserManageMapper;
import com.distribution.system.mapper.SysUserMapper;
import com.distribution.system.service.NoticeUserManageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static com.distribution.common.utils.SecurityUtils.getUserId;

/**
 * @author: GodLu
 * @create: 2024-11-05 10:09
 * @description:
 */
@Service
public class NoticeUserManageServiceImpl extends ServiceImpl<NoticeUserManageMapper, NoticeUserManage> implements NoticeUserManageService {
    @Resource
    SysUserMapper sysUserMapper;

    @Transactional
    @Override
    public int addNoticeToAllAgent(SysNotice notice) {
        List<Long> userIdList = getAgentUserIdList();
        List<NoticeUserManage> manageList = new ArrayList<>();
        userIdList.forEach(f -> {
            NoticeUserManage noticeUserManage = new NoticeUserManage();
            noticeUserManage.setUserId(f);
            noticeUserManage.setNoticeId(notice.getNoticeId());
            noticeUserManage.setStatus("0");
            noticeUserManage.setCreateTime(LocalDateTime.now());
            noticeUserManage.setUpdateTime(LocalDateTime.now());
            manageList.add(noticeUserManage);
        });
        if (manageList.isEmpty()) return -1;
        return saveOrUpdateBatch(manageList) ? 1 : -1;
    }

    private List<Long> getAgentUserIdList() {
        // 所有一二三级代理
        List<SysUser> sysUserList = sysUserMapper.selectUserListByRoleId(Arrays.asList(100L, 101L, 102L));
        return sysUserList.stream().map(SysUser::getUserId).collect(Collectors.toList());
    }

    @Override
    public int delNoticeUserManageById(Long noticeIds) {
        boolean flag = remove(new LambdaQueryWrapper<NoticeUserManage>().in(NoticeUserManage::getNoticeId, noticeIds));
        return flag ? 1 : -1;
    }

    @Override
    public void markReadByNoticeId(Long noticeId) {
        lambdaUpdate().eq(NoticeUserManage::getNoticeId, noticeId).eq(NoticeUserManage::getUserId, getUserId()).set(NoticeUserManage::getStatus, "1").update();
    }
}
